package com.esl.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.esl.model.admin.IPRecord;
import com.sina.sae.kvdb.SaeKV;
import com.sina.sae.kvdb.SaeKVUtil;

public class IPRecordFilter implements Filter {
	private SaeKV kv;

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		if (request.getSession().isNew()) {
			String ip=getIpAddr((HttpServletRequest) req);
			kv.set("T_IPRecord", SaeKVUtil.serializable(new IPRecord(ip)));
		}

		chain.doFilter(req, res);
	}

	public void init(FilterConfig config) throws ServletException {
		kv = new SaeKV();
		// 初始化服务
		kv.init();
	}

	public void destroy() {

	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}